/*
 * UART0
 * TX GPIOD18 AD19 function1
 * RX GPIOD14 AE19 function1
 * 
 * UART3
 * TX GPIOD21 W17 function1
 * RX GPIOD17 Y17 function1
 */

#include "../gpio.h"
#include "uart.h"

void uart0_init(int baud){

    GPIODALTFN0 &= ~((3 << 28));
    GPIODALTFN1 &= ~((3 << 4));
    GPIODOUTENB &= ~((1 << 18) | (1 << 14));

    GPIODALTFN0 |= ((1 << 28));
    GPIODALTFN1 |= ((1 << 4));
    GPIODOUTENB |= ((1 << 18));

    // 设置UART0时钟
    UARTCLKENB |= (1 << 2);
    UARTCLKGEN0L &= ~((7 << 2) | (0xFF << 5));
    UARTCLKGEN0L |= ((55 - 1) << 5);
    // UARTCLKGEN0L |= ((200 - 1) << 5);

    // 配置波特率 115200
    UARTIBRD &= ~0xFFFF;
    UARTIBRD |= 5;
    UARTFBRD &= ~0x3F;
    UARTFBRD |= 27;

    // 8N1
    UARTLCR_H &= ~((3 << 5) | (0x1F << 0));
    UARTLCR_H |= ((3 << 5));

    // UART TX RX使能
    UARTCR |= ((1 << 0) | (1 << 8) | (1 << 9));
}

void uart3_init(int baud){

    GPIODALTFN1 &= ~((3 << 2) | (3 << 10));
    GPIODOUTENB &= ~((1 << 21) | (1 << 17));

    GPIODALTFN1 |= ((1 << 2) | (1 << 10));
    GPIODOUTENB |= ((1 << 21));

    // 设置UART3时钟
    UART3CLKENB |= (1 << 2);
    UART3CLKGEN0L &= ~((7 << 2) | (0xFF << 5));
    UART3CLKGEN0L |= ((55 - 1) << 5);
    // UARTCLKGEN0L |= ((200 - 1) << 5);

    // 配置波特率 115200
    UARTIBRD_3 &= ~0xFFFF;
    UARTIBRD_3 |= 5;
    UARTFBRD_3 &= ~0x3F;
    UARTFBRD_3 |= 27;

    // 8N1
    UARTLCR_H_3 &= ~((3 << 5) | (0x1F << 0));
    UARTLCR_H_3 |= ((3 << 5));

    // UART TX RX使能
    UARTCR_3 |= ((1 << 0) | (1 << 8) | (1 << 9));
}

char my_getc(){

    // if((UARTFR >> 6) & 1){
    //     rec = UARTDR & 0xFF;
    // }
    while((UARTFR & (1 << 6)) == 0);
    return UARTDR;
}

void my_putc(char c){
    while(UARTFR & (1 << 3));
    UARTDR = c;
}

char my_getc_3(){

    // if((UARTFR >> 6) & 1){
    //     rec = UARTDR & 0xFF;
    // }
    while((UARTFR_3 & (1 << 6)) == 0);
    return UARTDR_3;
}

void my_putc_3(char c){
    while(UARTFR_3 & (1 << 3));
    UARTDR_3 = c;
}

void my_puts(char *p){
    int i = 0;

    while(p[++i] != 0){
        my_putc(p[i]);
    }
}

void raise(){
    
}

